package com.wlyuan.open.scanner.application.handler.incr;

import com.wlyuan.open.dto.OpenQuotationSyncDTO;
import com.wlyuan.open.scanner.application.async.AsyncOrderThreadUtils;
import com.wlyuan.open.scanner.application.task.quotation.QuotationTaskHandler;
import com.wlyuan.open.scanner.assembler.ScannerQuotationAssembler;
import com.wlyuan.open.scanner.constant.Constants;
import com.wlyuan.open.scanner.constant.ScannerCodeEnum;
import com.wlyuan.open.scanner.repository.QuotationRelationRepository;
import com.wlyuan.open.scanner.repository.QuotationRepository;
import com.wlyuan.open.scanner.utils.enums.order.OrderSrcClassEnum;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.apache.commons.collections4.ListUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Optional;
import java.util.concurrent.CountDownLatch;

/**
 * @author lijing
 * @description 报价 增量listener
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class QuotationIncrHandler extends BaseIncrHandler<OpenQuotationSyncDTO> {
    private final QuotationRepository quotationRepository;
    private final QuotationTaskHandler quotationTaskHandler;
    private final QuotationRelationRepository quotationRelationRepository;

    @Override
    public OpenQuotationSyncDTO process(Long orderId) {
        logger.info("报价增量同步：{}", orderId);
        return Optional.ofNullable(orderId).map(id -> {
            var quotation = quotationRepository.getByOrderId(id);
            return ScannerQuotationAssembler.assemble(quotation);
        }).orElse(null);
    }

    @Override
    public void incrByTenantId(Long tenantId) {
        quotationTaskHandler.handler(tenantId);
    }

    @Override
    public void incrByTime(Long tenantId, String startTime, String endTime) {
        var list = tenantId == null ? quotationRelationRepository.getByTime(startTime, endTime, OrderSrcClassEnum.CLIENT_ORDER.getValue().intValue()) : quotationRelationRepository.getByTenantIdTime(tenantId, startTime, endTime, OrderSrcClassEnum.CLIENT_ORDER.getValue().intValue());
        if (CollectionUtils.isEmpty(list)) {
            logger.info("根据时间{},{}数据为0", startTime, endTime);
            return;
        }
        logger.info("根据时间{},{}数据为：{}", startTime, endTime, list.size());
        var partitionList = ListUtils.partition(list, Constants.PAGE_SIZE);
        CountDownLatch countDownLatch = new CountDownLatch(partitionList.size());
        partitionList.parallelStream().forEach(partition -> {
            AsyncOrderThreadUtils.getInstance().excute(new Thread(() -> {
                partition.parallelStream().forEach(id -> increment(id));
                countDownLatch.countDown();
            }));
        });
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {

        }
        logger.info("同步完成");
    }

    @Override
    public String getSyncType() {
        return ScannerCodeEnum.QUOTATION.getVal();
    }


}
